package com.stephen.redisdemo.reference;

import java.lang.ref.SoftReference;

/**
 * @author: stephen
 * @create: 2020-03-03 14:38
 * @description: 软引用
 * 内存充足,不回收;内存不足,就回收
 */
public class SoftReferenceDemo {

    /**
     * 内存充足
     */
    public static void softRef_memory_enough() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;
        System.gc();
        System.out.println(o1);
        System.out.println(softReference.get());
    }

    /**
     * 内存不足
     * 故意产生大对象,并配置小内存,产生OOM
     * -Xmx5m -Xms5m -XX:+PrintGCDetails
     */
    public static void softRef_memory_not_enough() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;

        try {
            byte[] arr = new byte[30 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(o1);
            System.out.println(softReference.get());
        }
    }

    public static void main(String[] args) {
        // softRef_memory_enough();

        // softRef_memory_not_enough();
    }

}
